import { Button, DatePicker, Input, Message, Select, Table } from '@arco-design/web-react';
import { HasPermission } from '@src/components/ability';
import LoadingMask from '@src/components/loadingMask';
import { MenuTypes } from '@src/components/mainNavBar';
import SearchBar from '@src/components/searchBar';
import { IconAdd, IconDelete, IconRefresh } from '@src/components/svg/svgIcon';
import { dictTag, keepCopy } from '@src/components/tableColumn';
import TextButton from '@src/components/textButton';
import React, { useEffect, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import main from '../../../main';
import { AppStore } from '../../../types';
import useDict, { dictDataOptions } from '../../../utils/dict';
import usePageUtils from '../../../utils/pageUtils';
import { clearEmptyKey, onKeyEnter } from '../../../utils/utils';
import { apiRefreshDict } from './api';
import { Dict } from './types';

interface Props {
  currentRouteRecord: MenuTypes;
}

// 系统开关 状态
const SYS_NORMAL_DISABLED = 'sys_normal_disable';

// const model = 'system';
// const table = 'dict/type';

export default function DictListPage({ currentRouteRecord }: Props) {
  const pageUtils = usePageUtils({ model: 'system', table: 'dict/type', type: 'paginate' });
  const navigate = useNavigate();
  // 当前页面选中的数据列表
  const [tabSelectRows, setTabSelectRows] = useState<Dict[]>([]);
  const dictDatas = useDict(SYS_NORMAL_DISABLED);
  /// ---------------搜索栏数据 --按页面要求修改------------
  const [dictName, setDictName] = useState(pageUtils.params?.dictName ?? '');
  const [dictType, setDictType] = useState(pageUtils.params?.dictType ?? '');
  const [status, setStatus] = useState(pageUtils.params?.status ?? '');
  const [beginTime, setBeginTime] = useState(pageUtils.params?.params?.beginCreateTime ?? '');
  const [endTime, setEndTime] = useState(pageUtils.params?.params?.endCreateTime ?? '');
  ///----------------------------------------

  // 当前页需要的数据
  const list = useSelector((state: AppStore) => state.paginate[pageUtils.stateKey], shallowEqual);

  // 创建请求参数 及检索key 按页面要求修改
  function createParams() {
    return clearEmptyKey({
      dictName,
      dictType,
      status,
      params: { beginCreateTime: beginTime, endCreateTime: endTime },
      orderByColumn: 'createTime',
      isAsc: 'desc',
    });
  }
  // 需要随时刷新 创建参数的方法
  useEffect(() => {
    pageUtils.setFun(createParams);
  }, [createParams]); // eslint-disable-line

  // 页面初始化时请求数据
  useEffect(() => {
    pageUtils.handleRefreshData();
    main.setPageNum(pageUtils.pageTag, pageUtils.pageNum);
  }, []); //eslint-disable-line

  // 搜索
  function handleSearch() {
    setTabSelectRows([]);
    pageUtils.handleSearch();
  }

  // 重置
  function handleReset() {
    setTabSelectRows([]);
    setDictName('');
    setDictType('');
    setStatus('');
    setBeginTime('');
    setEndTime('');
    pageUtils.handleReset({ orderByColumn: 'createTime', isAsc: 'desc' });
  }

  // 组合详情路由
  function createDetailRoutePath(record: Dict | string) {
    let id = typeof record === 'string' ? record : record.dictId;
    return `${currentRouteRecord.link!.replace('/index', '/detail')}/${id}`;
  }

  // 列表项双击事件 一般是进详情
  function handleDoubleClick(record: Dict) {
    if (currentRouteRecord.isDetail) {
      navigate(createDetailRoutePath(record));
    }
  }

  // 创建
  function handleCreate() {
    navigate(createDetailRoutePath('create'));
  }

  // 修改 操作列内的修改
  function handleEdit(record?: Dict) {
    if (record) {
      navigate(createDetailRoutePath(record));
    }
  }

  // 删除 弹窗确认
  async function handleDelete(record?: Dict) {
    let datas = record ? [record] : tabSelectRows || [];
    pageUtils.handleDelete(datas.map((i) => i.dictId!));
  }

  // 列表项有选择变动
  function handleTabSelectChange(selectedRowKeys: React.Key[], selectedRows: Dict[]) {
    setTabSelectRows(selectedRows);
  }
  ///-----------额外数据 / 方法-------------------

  // 刷新缓存
  async function handleRefreshCache() {
    LoadingMask.show('正在刷新...');

    try {
      let res = await apiRefreshDict();
      let data = res.data;
      if (data.code === 200) {
        Message.success('刷新成功');
      } else {
        Message.error(data.msg ?? '刷新失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '刷新失败');
    } finally {
      LoadingMask.hide();
    }
  }
  ///-------------------------------------

  let dataSource: Dict[] = list?.results || [];
  dataSource = dataSource.map((item) => Object.assign({}, item, { key: item.dictId }));
  // 定义表格内的列
  const columns = [
    {
      title: '字典编号',
      dataIndex: 'dictId',
      key: 'dictId',
    },
    {
      title: '字典名称',
      dataIndex: 'dictName',
      key: 'dictName',
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
      key: 'dictType',
      render: keepCopy,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) => dictTag(v, dictDatas[SYS_NORMAL_DISABLED]),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      render: (_: any, record: Dict) => (
        <div className="d-flex-r jc-start text-primary-color">
          <TextButton text="编辑" permission={['system:dict:edit']} onClick={() => handleEdit(record)} />
          <TextButton text="删除" red permission={['system:dict:remove']} onClick={() => handleDelete(record)} />
        </div>
      ),
    },
  ];

  return (
    <div className="page list-page">
      <SearchBar onConfirm={handleSearch} onReset={handleReset}>
        <Input
          allowClear
          className="mr-20 mb-20 search-input"
          placeholder="字典名称"
          value={dictName}
          onKeyUp={onKeyEnter(handleSearch)}
          onChange={(v) => setDictName(v)}
        />
        <Input
          allowClear
          className="mr-20 mb-20 search-input"
          placeholder="字典类型"
          value={dictType}
          onKeyUp={onKeyEnter(handleSearch)}
          onChange={(v) => setDictType(v)}
        />
        <Select
          className="mr-20 mb-20 search-select"
          allowClear
          placeholder="请选择状态"
          value={!status ? undefined : status}
          options={dictDataOptions(dictDatas[SYS_NORMAL_DISABLED])}
          onChange={(v) => setStatus(v)}
        />
        <DatePicker.RangePicker
          allowClear
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          className="mr-20 mb-20 search-range-picker"
          placeholder={['开始时间', '结束时间']}
          value={!beginTime || !endTime ? undefined : [beginTime, endTime]}
          onChange={(dates) => {
            setBeginTime(dates?.[0] || '');
            setEndTime(dates?.[1] || '');
          }}
        />
      </SearchBar>
      <div className="page-content m-20">
        <div className="action-bar">
          <div className="flex-1" />
          <HasPermission permission={['system:dict:remove']}>
            <Button icon={<IconRefresh />} className="ml-20" type="outline" onClick={() => handleRefreshCache()}>
              刷新缓存
            </Button>
          </HasPermission>
          <HasPermission permission={['system:dict:add']}>
            <Button icon={<IconAdd />} className="ml-20" type="primary" onClick={handleCreate}>
              新增
            </Button>
          </HasPermission>
          <HasPermission permission={['system:dict:remove']}>
            <Button
              icon={<IconDelete />}
              className="ml-20"
              type="primary"
              status="danger"
              onClick={() => handleDelete()}
            >
              删除
            </Button>
          </HasPermission>
        </div>
        <Table
          className="table"
          rowSelection={{ type: 'checkbox', onChange: handleTabSelectChange }}
          data={dataSource}
          columns={columns}
          pagination={{
            className: 'pagination-block',
            total: list?.total || 1,
            current: pageUtils.pageNum,
            pageSize: pageUtils.pageSize,
            showJumper: true,
            sizeOptions: main.defaultPageSizeOptions,
            showTotal: (total) => `共${total}条`,
            size: 'small',
            onChange: pageUtils.handlePageAndSizeChange,
          }}
          loading={!list || (list?.fetching && !list?.loaded)}
          onRow={(record: Dict) => ({
            onDoubleClick: () => handleDoubleClick(record),
          })}
        />
      </div>
    </div>
  );
}
